package com.deloitte.payrollmgtsys.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.deloitte.payrollmgtsys.util.PasswordGenerator;

/**
 * Responsible for creating user account via REST call to activiti-rest.
 * 
 * @author muwang
 *
 */
@Controller
public class CreateUserServlet {

	@RequestMapping("/createUser")
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		HttpURLConnection connection = null;
		BufferedReader rd = null;
		StringBuilder sb = null;
		String line = null;
		URL serverAddress = null;
		InputStream is = null;
		OutputStream os = null;
		
		String user = request.getParameter("user");
		String originUrl = request.getParameter("url");
		
		String url = originUrl.split("service")[0] + "service/user";
		String password = PasswordGenerator.getPassword(user);

		StringBuffer param = new StringBuffer(200);
		url = url + "?access_token=" + request.getSession().getAttribute("access_token");
		param.append("{ \"id\": \"" + user + "\", ")
				.append("\"firstName\": \"" + request.getSession().getAttribute("userFirstname") + "\", ")
				.append("\"lastName\": \"" + request.getSession().getAttribute("userSurname") +"\", ")
				.append("\"email\": \"" + user + "\", ")
				.append("\"password\": \"" + password + "\" } ");

		try {
			serverAddress = new URL(url);
			connection = (HttpURLConnection) serverAddress.openConnection();

			connection.setRequestMethod("PUT");
			connection.addRequestProperty("Content-Type", "application/json");
			connection.setDoOutput(true);
			connection.setReadTimeout(10000);

			os = connection.getOutputStream();
			os.write(param.toString().getBytes());

			connection.connect();

			is = connection.getInputStream();
			rd = new BufferedReader(new InputStreamReader(is));
			sb = new StringBuilder();
			while ((line = rd.readLine()) != null) {
				sb.append(line + '\n');
			}
		} finally {
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
		}

		response.setStatus(connection.getResponseCode());
		response.setContentType("text/plain");
		response.getWriter().println(sb);
	}
}
